#include <queue>
#include <vector>
using namespace std;

class Solution
{
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
public:
    int maxDistance(vector<vector<int>>& grid)
    {
        int ret = -1;
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> dis(m, vector<int>(n, -1));
        queue<pair<int, int>> q;
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                if(grid[i][j]==1)
                {
                    dis[i][j] = 0;
                    q.emplace(i, j);
                }

        while(!q.empty())
        {
            auto [a, b] = q.front();
            q.pop();
            for(int k=0; k<4; k++)
            {
                int x = a+dx[k], y = b+dy[k];
                if(x>=0 && x<m && y>=0 && y<n && dis[x][y]==-1)
                {
                    dis[x][y] = dis[a][b]+1;
                    q.emplace(x, y);
                    ret = max(ret, dis[x][y]);
                }
            }
        }
        return ret;
    }
};